package plgnet

import (
	"dgo/MyProj/PrjHttpClt"
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/utils"
	"dgo/plg/plgbase"
	"fmt"
	"gitee.com/ymofen/gobase/golog"
	"gitee.com/ymofen/supervalue"
	"sync/atomic"
	"time"
)

type PlgHttpCltNotify struct {
	plgbase.PlgBase
	url                 string
	lastRequestURL      string
	check_list_flag     int
	request_succ_n      int
	startflag           uint32
	last_request_task_t time.Time
	last_resp           string
	last_resp_t         time.Time
}

func (this *PlgHttpCltNotify) Request() {
	url := plgbase.ReplacePlaceholderForFileName(this.url)
	json, err := PrjHttpClt.GetUrlAsJSON(url)
	if err != nil {
		this.last_resp = fmt.Sprintf("接口访问异常:%s, url:%s", err.Error(), url)
		this.last_resp_t = time.Now()
		golog.Warnf("请求异常:%s, url:%s", err.Error(), url)
		return
	}

	this.last_resp = json.AsJSONString(false)
	this.last_resp_t = time.Now()
	if json.IntByName("code", 0) != -1 {
		this.request_succ_n++
	}
	this.lastRequestURL = url
}

func (this *PlgHttpCltNotify) OnHttpStatus(rec *PlgHttpRec) (rval interface{}, errcode int, err error) {

	json := wrapper.NewSVObject()
	json.SetKeyValue("request_succ_n", this.request_succ_n)
	json.SetKeyValue("startflag", this.startflag)
	json.SetKeyValue("last_request_task_t", utils.DateTimeString2(this.last_request_task_t))
	json.SetKeyValue("last_resp", this.last_resp)
	json.SetKeyValue("last-resp-t", utils.DateTimeString2(this.last_resp_t))
	json.SetKeyValue("last-url", this.lastRequestURL)
	PrjHttpUtils.JSON2TableRec(rec.RespW, "", json.String())

	return
}

func (this *PlgHttpCltNotify) ReloadConf(conf *wrapper.SuperValue) error {
	conf.CheckStrFunc("url", func(strv string) {
		this.url = plgbase.ReplacePlaceholderForFileName(strv)
		if this.lastRequestURL != this.url {
			this.request_succ_n = 0
		}

	})

	if conf.IntByName("force-reload", 0) == 1 {
		this.request_succ_n = 0
	}

	if atomic.CompareAndSwapUint32(&this.startflag, 0, 1) {
		utils.AddTaskFxiedInterval(this, time.Second*10, func() bool {
			this.last_request_task_t = time.Now()
			url := plgbase.ReplacePlaceholderForFileName(this.url)
			if url != this.lastRequestURL {
				this.request_succ_n = 0
			}

			if this.request_succ_n == 0 {
				this.Request()
			}

			return this.startflag == 1
		})
	}
	return nil
}

func (this *PlgHttpCltNotify) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		this.startflag = 0
	}
	return
}

func CreatePlgHttpCltNotifyFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &PlgHttpCltNotify{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	rval = obj
	return
}
